package com.heima.datasync.service.impl;

import com.heima.common.constants.es.EsConstants;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.vos.SearchArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    EsService esService;
    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult dataInit() {
        boolean existIndex = esService.existIndex(EsConstants.ARTICLE_INDEX_NAME);
        if (!existIndex){
            esService.createIndex(EsConstants.ARTICLE_INDEX,EsConstants.ARTICLE_INDEX_NAME);
        }
        List<ApArticle> articleList = apArticleMapper.selectAllArticles();
        List<SearchArticleVO> searchArticleVOList = articleList.stream().map(apArticle -> {
            SearchArticleVO searchArticleVO = new SearchArticleVO();
            BeanUtils.copyProperties(apArticle, searchArticleVO);
            return searchArticleVO;
        }).collect(Collectors.toList());
        esService.saveBatch(searchArticleVOList,EsConstants.ARTICLE_INDEX_NAME);
        return ResponseResult.okResult();
    }

}
